import fcntl
import os
from pathlib import Path
import time

class FileLock:
    def __init__(self, lockfile):
        self.lockfile = lockfile
        self.fd = None
        
    def acquire(self):
        try:
            # 创建父目录
            lock_dir = Path(self.lockfile).parent
            # print(f"尝试创建目录: {lock_dir}")
            lock_dir.mkdir(parents=True, exist_ok=True, mode=0o755)
            
            # 检查目录权限
            if not os.access(lock_dir, os.W_OK):
                raise PermissionError(f"无写入权限: {lock_dir}")
            
            # print(f"尝试创建锁文件: {self.lockfile}")
            self.fd = open(self.lockfile, 'w')
            try:
                fcntl.flock(self.fd, fcntl.LOCK_EX)
                return True
            except IOError:
                return False
                
            
        except Exception as e:
            print(f"获取锁失败: {str(e)}")
            if self.fd:
                self.fd.close()
            return False

    def release(self):
        if self.fd:
            try:
                fcntl.flock(self.fd, fcntl.LOCK_UN)
                self.fd.close()
            except Exception as e:
                print(f"释放锁失败: {str(e)}")
            finally:
                self.fd = None

    def __enter__(self):
        self.acquire()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.release()

